Search


📜 [專欄新文章] Solidity Weekly #16
✍️ mingd...

  • Share this:


📜 [專欄新文章] Solidity Weekly #16
✍️ mingderwang
📥 歡迎投稿: https://medium.com/taipei-ethereum-meetup #徵技術分享文 #使用心得 #教學文 #medium

Expo (React Native) + web3.js 1.0.x 開發手機 dApps

今天要介紹如何利用 Expo,來撰寫手機 dApp。基本上,如果想做到去中心化的 dApp,期望能將 Javascript app 能盡可能的包裹成單一檔案,用去中心化檔案儲存空間,讓手機或網頁直接下載來執行。手機版的 App,也可用 Expo 做到類似的結果,但目前 Expo 還是有點中心化;當然利用 cipherbrowser 或 status.im 等方式開發也行,只要你不怕被 vendor lock-in。

Expo 是一種 MIT license 的開放源始碼,讓 React Native 開發與部屬更為簡單,讓用戶只要先下載 iOS 或 Android 的 Expo clients。就很容易透過 exp://xxx 的 URI 來執行。因為 React Native 跟 web3.js 都是用 Javascript 語言,因此很容易整合。(註:web3.js 也不是唯一連區塊鏈的方法,只是搭配 Remix,能產生 web3 程式片段,所以比較方便)

但由於 React Native 非 100% 與 node.js 相容,因此有些 workarounds 要做,例如 node 內建 standard library 裡的 crypto (註 2),Buffer 等 React Native 就沒有,所以這裏還不是很方便。(喜歡 truffle 的人,也可參考 react-native-box 來做,但也還沒很成熟)

Mobile dApp 有個問題是,你(用戶)沒有 localhost 自己的 node 當成 web3 provider 可以連線到 Ethereum 區塊鏈。所以有幾種選擇,最簡單的就是要再相信某一個 node,這裡用 infura (與 Metamask 同一家公司),也許還要搭配其他方法,讓這 dApp 不要依賴任何 server 也能運作。但如果要用到 HDWallet,還是要用 truffle-hdwallet-provider 來當 web3 provider,也能同時避開沒有 crypto 的問題。
使用 Expo 開發畫面
註 1:直接用 React Native 開發,不容易除錯,且速度慢。所以建議程式邏輯可以考慮用 React Native for Web 在 CodeSandbox.io 先做開發和測試,最後再搬到 Expo 的 React Native 裡。(或直接在 codesandbox.io 開發 Expo 程式也行)

CodeSandbox

註 2:例如當在 Expo 的環境裡使用到 web3.eth.accounts.create() 時,會出現以下 error,但其他地方(Condsandbox)不會。

解決方法,不要用 web3 provider 改用 truffle-hdwallet-provider (在 React Native 裡要用 Promise.promisifyAll 繞過問題)

var HDWalletProvider = require("truffle-hdwallet-provider"); var mnemonic = "manage velvet tide tube object spin identify neither foot together wagon tip"; var hd = new HDWalletProvider(mnemonic, "https://mainnet.infura.io/"); web3 = new Web3(hd); Promise.promisifyAll(web3.eth); let accounts = await web3.eth.getAccountsAsync();

Solidity Weekly #16 was originally published in Taipei Ethereum Meetup on Medium, where people are continuing the conversation by highlighting and responding to this story.

👏 歡迎轉載分享鼓掌


Tags:

About author
not provided
We have regular meeting twice per month on discussing blockchain technology, smart contracts and DApps development! We would love to have you join us!
View all posts